﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

using JigsawService.Parsers;
using JigsawService.Utility;

namespace JigsawService.DataAccess.Usage
{
    public class APIUsageDA : JigsawBase
    {
        APIMessage _apimessage;
        string _dbstr;

        public APIUsageDA(APIMessage apiMessage)
        {
            _apimessage = apiMessage;
            // read the database connection string from the web.config file
            _dbstr = ConfigurationManager.AppSettings["UsageDB"].ToString();
        }

        /// <summary>
        /// this method and underlying database table is used exclusively to measure API usage and performance.
        /// No unique constraint or referential integrity tests are required.
        /// </summary>
        public void APIUsage()
        {
            _apimessage.StateMessage = "APIUsage SaveEvent: ";
            using (SqlConnection sqlConn = new SqlConnection(_dbstr))
            {
                sqlConn.Open();
                SqlTransaction sqlTran = sqlConn.BeginTransaction();
                SqlCommand sqlCmd = new SqlCommand();
                sqlCmd.Connection = sqlConn;
                sqlCmd.Transaction = sqlTran;

                // define parameterized dml
                string dmlCmd = "Insert Into APIUsage" +
                                " (UserID, SessionID, Location, APIFullName, RequestTime, StartTime, EndTime)" +
                                " Values (@UserID, @SessionID, @Location, @APIFullName, @RequestTime, @StartTime, @EndTime)";

                // assign input parameters as values to the dml parameters
                sqlCmd.Parameters.Add("@UserID", SqlDbType.VarChar, 50).Value = _apimessage.UserID;
                sqlCmd.Parameters.Add("@SessionID", SqlDbType.VarChar, 50).Value = _apimessage.SessionGUID;
                sqlCmd.Parameters.Add("@Location", SqlDbType.VarChar, 50).Value = _apimessage.Location;
                sqlCmd.Parameters.Add("@APIFullName", SqlDbType.VarChar, 100).Value = _apimessage.APIString;
                sqlCmd.Parameters.Add("@RequestTime", SqlDbType.Decimal).Value = Convert.ToDecimal(_apimessage.RequestTime);
                sqlCmd.Parameters.Add("@StartTime", SqlDbType.Decimal).Value = Convert.ToDecimal(_apimessage.StartTime);
                sqlCmd.Parameters.Add("@EndTime", SqlDbType.Decimal).Value = Convert.ToDecimal(_apimessage.EndTime);

                try
                {
                    // assign the dml to the sql command object, and execute the transaction
                    sqlCmd.CommandText = dmlCmd;
                    sqlCmd.ExecuteNonQuery();
                    sqlTran.Commit();
                    SetSuccessResult("New APIUsage record saved.", "text", _apimessage);
                }
                catch (Exception ex)
                {
                    // rollback transaction and close connection
                    if (sqlConn.State == ConnectionState.Open)
                    {
                        sqlTran.Rollback();
                        sqlConn.Close();
                    }
                    // rethrow error, to be handled at the service level
                    throw;
                }
            }
        }


    }
}